<template>
	<view class="circle-list">
		<!-- 加载状态 -->
		<view class="loading-container" v-if="loading && circleList.length === 0">
			<view class="loading-content">
				<view class="loading-spinner"></view>
				<text class="loading-text">加载中...</text>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-container" v-if="!loading && circleList.length === 0">
			<view class="empty-content">
				<view class="empty-icon">
					<text class="cuIcon-community"></text>
				</view>
				<text class="empty-title">暂无内容</text>
				<text class="empty-desc">快来发布第一条动态吧</text>
				<view class="empty-action" @click="createPost">
					<text class="action-text">发布动态</text>
				</view>
			</view>
		</view>

		<!-- 帖子列表 -->
		<view class="post-list" v-if="circleList.length > 0">
			<view class="post-card" v-for="item in circleList" :key="item._id">
				<!-- 帖子头部 -->
				<view class="post-header" @click="goPage(item)">
					<view class="user-info">
						<view class="avatar-container">
							<image :src="item.author.avatar || config.commonUrl + '/avt.png'" class="user-avatar"
								mode="aspectFill" />
							<view class="user-badge" v-if="item.author.isCertified">
								<text class="badge-icon">✓</text>
							</view>
						</view>
						<view class="user-details">
							<text class="user-name">{{item.author.nickname || '未知用户'}}</text>
							<view class="post-meta">
								<text class="post-time">{{ formatDate(item.createdAt) }}</text>
								<text class="post-location" v-if="item.author.community && item.author.community.name">
									<text class="location-icon">📍</text>
									{{item.author.community.name}}
								</text>
							</view>
						</view>
					</view>

					<!-- 操作按钮 -->
					<view class="post-actions" v-if="isMe(item)">
						<view class="action-dropdown" v-if="item.status !== 'pending'">
							<view class="action-btn" @click.stop="handleActionClick($event, item)">
								<text class="action-icon">⋯</text>
							</view>
							<view class="dropdown-menu" v-if="item.showMenu">
								<view class="menu-item" @click="handleMenuItemClick('edit', item)">
									<text class="menu-icon">✏️</text>
									<text class="menu-text">编辑</text>
								</view>
								<view class="menu-item delete" @click="handleMenuItemClick('delete', item)">
									<text class="menu-icon">🗑️</text>
									<text class="menu-text">删除</text>
								</view>
							</view>
						</view>
						<view class="status-badge" v-else>
							<text
								class="status-text">{{item.status === 'pending' ? '审核中' : item.status === 'rejected' ? '未通过' : item.status === 'approved' ? '已通过' : '未知'}}</text>
						</view>
					</view>
				</view>

				<!-- 帖子内容 -->
				<view class="post-content" @click="handleContentClick(item)">
					<!-- 标题 -->
					<view class="post-title" v-if="item.title">
						<text class="title-text">{{item.title}}</text>
					</view>

					<!-- 正文 -->
					<view class="post-text" v-if="item.content">
						<text class="text-content">{{item.content}}</text>
					</view>

					<!-- 图片网格 -->
					<view class="image-grid" v-if="item.images && item.images.length > 0">
						<view class="image-item" v-for="(image, imgIndex) in item.images.slice(0, 3)" :key="imgIndex"
							@click.stop="previewImage(item.images, imgIndex)">
							<image :src="image" mode="aspectFill" class="grid-image" />
							<view class="image-overlay">
								<text class="overlay-text">点击查看</text>
							</view>
							<!-- 图片总数标签 -->
							<view class="image-count-badge" v-if="imgIndex === 2 && item.images.length > 3">
								<text class="count-text">+{{item.images.length - 3}}</text>
							</view>
						</view>
					</view>

					<!-- 闲置信息 -->
					<view class="idle-info" v-if="item.idleInfo && item.idleInfo.condition">
						<view class="info-header">
							<text class="info-title">闲置物品信息</text>
						</view>
						<view class="info-grid">
							<view class="info-item">
								<text class="info-label">新旧程度</text>
								<text class="info-value">{{item.idleInfo.condition || '未知'}}</text>
							</view>
							<view class="info-item">
								<text class="info-label">原价</text>
								<text class="info-value original-price">¥{{item.idleInfo.originalPrice || '0'}}</text>
							</view>
							<view class="info-item">
								<text class="info-label">现价</text>
								<text class="info-value current-price">¥{{item.idleInfo.price || '0'}}</text>
							</view>
						</view>
					</view>

					<!-- 失物招领信息 -->
					<view class="lost-found-info" v-if="item.lostFoundInfo && item.lostFoundInfo.type">
						<view class="info-header">
							<text class="info-title">{{item.lostFoundInfo.type === 'lost' ? '失物信息' : '招领信息'}}</text>
						</view>
						<view class="info-list">
							<view class="info-row" v-if="item.lostFoundInfo.location">
								<text class="info-label">地点</text>
								<text class="info-value">{{item.lostFoundInfo.location || '未知'}}</text>
							</view>
							<view class="info-row" v-if="item.lostFoundInfo.time">
								<text class="info-label">时间</text>
								<text class="info-value">{{formatLostFoundTime(item.lostFoundInfo.time)}}</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 帖子底部 -->
				<view class="post-footer">
					<view class="post-tags">
						<view class="type-tag"
							:class="item.type === '邻里日常' ? 'type-daily' : item.type === '失物招领' ? 'type-lost' : 'type-idle'">
							<text
								class="tag-icon">{{ item.type === '邻里日常' ? '🏠' : item.type === '失物招领' ? '🔍' : '🛍️' }}</text>
							<text class="tag-text">{{item.type}}</text>
						</view>
					</view>

					<view class="post-stats">
						<view class="stat-item" @click="goPage(item)">
							<text class="stat-icon">👁️</text>
							<text class="stat-count">{{item.viewCount || 0}}</text>
						</view>
						<view class="stat-item" @click="likePost(item)">
							<text class="stat-icon" :class="{'liked': item.isLiked}">❤️</text>
							<text class="stat-count">{{item.likeCount || 0}}</text>
						</view>
						<view class="stat-item" @click="goPage(item)">
							<text class="stat-icon">💬</text>
							<text class="stat-count">{{item.commentCount || 0}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 加载更多 -->
		<view class="load-more" v-if="loading && circleList.length > 0">
			<view class="loading-content">
				<view class="loading-spinner small"></view>
				<text class="loading-text">加载更多...</text>
			</view>
		</view>

		<!-- 删除确认弹窗 -->
		<uni-popup ref="popup" type="dialog">
			<uni-popup-dialog mode="base" type="error" title="确认删除?" confirmText="确认" cancelText="取消"
				@confirm="confirmDelete" />
		</uni-popup>

		<!-- 菜单遮罩层 -->
		<view class="menu-mask" v-if="hasMenuOpen" @click="hideAllMenus"></view>
	</view>
</template>

<script>
	import config from '@/config/config';

	export default {
		props: ['circleList', 'tabType', 'userInfo', 'loading'],
		data() {
			return {
				config,
				circleItem: {},
			};
		},
		computed: {
			hasMenuOpen() {
				return this.circleList.some(item => item.showMenu)
			}
		},

		methods: {
			goPage(item) {
				this.hideAllMenus()
				// 然后跳转页面
				this.$router.smartNavigate(`/pages/circlePages/circleInfo?id=${item._id}`, 'navigateTo')
			},
			editItem(item) {
				this.hideAllMenus()
				this.$store.commit('setEditCircle', item)
				this.$router.smartNavigate(`/pages/circlePages/editCircle?type=${this.circleType(this.tabType.id)}`, 'navigateTo')
			},
			deleteItem(item) {
				this.hideAllMenus()
				this.circleItem = item
				this.$refs.popup.open()
			},
			confirmDelete() {
				this.$emit("deleteCircleItem", this.circleItem)
				this.$refs.popup.close()
			},
			likePost(item) {
				this.$emit("likeCircle", item)
			},
			previewImage(images, current) {
				// 确保图片URL是完整的
				const fullUrls = images.map(img => {
					if (img.startsWith('http')) {
						return img
					} else {
						return this.config.commonUrl + img
					}
				})

				uni.previewImage({
					urls: fullUrls,
					current: fullUrls[current] || fullUrls[0]
				})
			},
			showActionMenu(item) {
				// 隐藏其他菜单
				this.hideAllMenus()
				// 显示当前菜单
				this.$set(item, 'showMenu', true)
			},
			hideAllMenus() {
				this.circleList.forEach(item => {
					this.$set(item, 'showMenu', false)
				})
			},
			createPost() {
				this.$router.smartNavigate('/pages/circlePages/editCircle', 'navigateTo')
			},
			isMe(item) {
				return item.author._id == this.userInfo._id
			},
			circleType(type) {
				const typeMap = {
					'1': 'A',
					'2': 'B',
					'3': 'C'
				}
				return typeMap[type.toString()] || 'A'
			},
			formatDate(dateString) {
				if (!dateString) return ''

				const date = new Date(dateString)
				const now = new Date()
				const diff = Math.floor((now - date) / 1000)

				if (diff < 60) return '刚刚'
				if (diff < 3600) return `${Math.floor(diff / 60)}分钟前`
				if (diff < 86400) return `${Math.floor(diff / 3600)}小时前`

				if (date.toDateString() === now.toDateString()) {
					return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
				}

				if (date.getFullYear() === now.getFullYear()) {
					return `${date.getMonth() + 1}月${date.getDate()}日`
				}

				return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
			},
			// 格式化招领信息时间，格式：2025-07-24 11:04
			formatLostFoundTime(dateString) {
				if (!dateString) return '未知'

				const date = new Date(dateString)

				// 检查日期是否有效
				if (isNaN(date.getTime())) return '未知'

				const year = date.getFullYear()
				const month = (date.getMonth() + 1).toString().padStart(2, '0')
				const day = date.getDate().toString().padStart(2, '0')
				const hours = date.getHours().toString().padStart(2, '0')
				const minutes = date.getMinutes().toString().padStart(2, '0')

				return `${year}-${month}-${day} ${hours}:${minutes}`
			},
			handleContentClick(item) {
				this.hideAllMenus()
				this.goPage(item)
			},
			// 点击操作按钮时阻止事件冒泡
			handleActionClick(event, item) {
				event.stopPropagation()
				// 如果当前菜单已显示，则隐藏；否则显示
				if (item.showMenu) {
					this.$set(item, 'showMenu', false)
				} else {
					this.showActionMenu(item)
				}
			},
			// 点击菜单项时隐藏菜单
			handleMenuItemClick(action, item) {
				this.hideAllMenus()
				if (action === 'edit') {
					this.editItem(item)
				} else if (action === 'delete') {
					this.deleteItem(item)
				}
			}
		},
		mounted() {
			// 组件挂载完成
		}
	}
</script>

<style lang="scss" scoped>
	.circle-list {
		padding: 0 24rpx;
	}

	.loading-container,
	.empty-container {
		display: flex;
		align-items: center;
		justify-content: center;
		min-height: 300rpx;

		.loading-content,
		.empty-content {
			text-align: center;

			.loading-spinner {
				width: 50rpx;
				height: 50rpx;
				border: 3rpx solid #f3f3f3;
				border-top: 3rpx solid #FE6100;
				border-radius: 50%;
				animation: spin 1s linear infinite;
				margin: 0 auto 20rpx;

				&.small {
					width: 32rpx;
					height: 32rpx;
					border-width: 2rpx;
				}
			}

			.loading-text {
				font-size: 26rpx;
				color: #8F97A2;
			}

			.empty-icon {
				font-size: 100rpx;
				color: #c0c4cc;
				margin-bottom: 24rpx;
			}

			.empty-title {
				display: block;
				font-size: 30rpx;
				color: #2C2622;
				font-weight: 600;
				margin-bottom: 12rpx;
			}

			.empty-desc {
				display: block;
				font-size: 26rpx;
				color: #8F97A2;
				margin-bottom: 36rpx;
			}

			.empty-action {
				display: inline-block;
				padding: 20rpx 40rpx;
				background: #FE6100;
				border-radius: 40rpx;

				.action-text {
					color: #fff;
					font-size: 26rpx;
					font-weight: 500;
				}
			}
		}
	}

	.post-list {
		.post-card {
			background: #fff;
			border-radius: 20rpx;
			margin-bottom: 24rpx;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
			overflow: hidden;
		}
	}

	.post-header {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		padding: 24rpx;
		border-bottom: 1rpx solid #f0f0f0;

		.user-info {
			display: flex;
			align-items: center;
			flex: 1;

			.avatar-container {
				position: relative;
				margin-right: 20rpx;

				.user-avatar {
					width: 64rpx;
					height: 64rpx;
					border-radius: 50%;
					border: 2rpx solid #fff;
					box-shadow: 0 1rpx 6rpx rgba(0, 0, 0, 0.08);
				}

				.user-badge {
					position: absolute;
					bottom: -1rpx;
					right: -1rpx;
					width: 24rpx;
					height: 24rpx;
					background: #52c41a;
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
					border: 2rpx solid #fff;

					.badge-icon {
						color: #fff;
						font-size: 14rpx;
						font-weight: bold;
					}
				}
			}

			.user-details {
				flex: 1;

				.user-name {
					display: block;
					font-size: 28rpx;
					font-weight: 600;
					color: #2C2622;
					margin-bottom: 6rpx;
				}

				.post-meta {
					display: flex;
					align-items: center;
					flex-wrap: wrap;
					gap: 12rpx;

					.post-time {
						font-size: 22rpx;
						color: #8F97A2;
					}

					.post-location {
						display: flex;
						align-items: center;
						font-size: 22rpx;
						color: #8F97A2;

						.location-icon {
							margin-right: 3rpx;
						}
					}
				}
			}
		}

		.post-actions {
			position: relative;

			.action-dropdown {
				.action-btn {
					width: 56rpx;
					height: 56rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					border-radius: 50%;
					background: #f8f9fa;

					.action-icon {
						font-size: 28rpx;
						color: #666;
						transform: rotate(90deg);
					}
				}

				.dropdown-menu {
					position: absolute;
					top: 100%;
					right: 0;
					background: #fff;
					border-radius: 12rpx;
					box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.12);
					padding: 16rpx 0;
					min-width: 160rpx;
					z-index: 100;

					.menu-item {
						display: flex;
						align-items: center;
						justify-content: flex-start;
						padding: 20rpx 24rpx;
						transition: background 0.2s ease;
						white-space: nowrap;

						&:active {
							background: #f8f9fa;
						}

						&.delete {
							color: #ff4d4f;
						}

						.menu-icon {
							margin-right: 12rpx;
							font-size: 24rpx;
							flex-shrink: 0;
						}

						.menu-text {
							font-size: 26rpx;
							color: inherit;
							line-height: 1;
						}
					}
				}
			}

			.status-badge {
				padding: 12rpx 24rpx;
				background: #fff7e6;
				border-radius: 20rpx;

				.status-text {
					font-size: 24rpx;
					color: #d46b08;
					font-weight: 500;
				}
			}
		}
	}

	.post-content {
		padding: 24rpx;

		.post-title {
			margin-bottom: 20rpx;

			.title-text {
				font-size: 32rpx;
				font-weight: 600;
				color: #2C2622;
				line-height: 1.4;
			}
		}

		.post-text {
			margin-bottom: 20rpx;

			.text-content {
				font-size: 28rpx;
				color: #2C2622;
				line-height: 1.6;
			}
		}

		.image-grid {
			display: flex;
			gap: 6rpx;
			margin-bottom: 20rpx;
			overflow-x: auto;
			scrollbar-width: none;
			/* Firefox */
			-ms-overflow-style: none;
			/* IE and Edge */

			&::-webkit-scrollbar {
				display: none;
				/* Chrome, Safari and Opera */
			}

			.image-item {
				position: relative;
				border-radius: 12rpx;
				overflow: hidden;
				flex-shrink: 0;
				width: 200rpx;
				height: 200rpx;

				.grid-image {
					width: 100%;
					height: 100%;
				}

				.image-overlay {
					position: absolute;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					background: rgba(0, 0, 0, 0.3);
					display: flex;
					align-items: center;
					justify-content: center;
					opacity: 0;
					transition: opacity 0.3s ease;

					.overlay-text {
						color: #fff;
						font-size: 22rpx;
						background: rgba(0, 0, 0, 0.7);
						padding: 8rpx 16rpx;
						border-radius: 16rpx;
					}
				}

				&:active .image-overlay {
					opacity: 1;
				}

				.image-count-badge {
					position: absolute;
					top: 8rpx;
					right: 8rpx;
					background: rgba(0, 0, 0, 0.6);
					border-radius: 12rpx;
					padding: 4rpx 10rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					z-index: 1;

					.count-text {
						color: #fff;
						font-size: 20rpx;
						font-weight: bold;
					}
				}
			}
		}

		.idle-info,
		.lost-found-info {
			background: #f8f9fa;
			border-radius: 16rpx;
			padding: 24rpx;
			margin-bottom: 24rpx;

			.info-header {
				margin-bottom: 16rpx;

				.info-title {
					font-size: 28rpx;
					font-weight: 600;
					color: #2C2622;
				}
			}

			.info-grid {
				display: grid;
				grid-template-columns: 1fr 1fr 1fr;
				gap: 16rpx;

				.info-item {
					text-align: center;

					.info-label {
						display: block;
						font-size: 24rpx;
						color: #8F97A2;
						margin-bottom: 8rpx;
					}

					.info-value {
						display: block;
						font-size: 28rpx;
						font-weight: 600;
						color: #2C2622;

						&.original-price {
							color: #8F97A2;
							text-decoration: line-through;
						}

						&.current-price {
							color: #ff4d4f;
						}
					}
				}
			}

			.info-list {
				.info-row {
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-bottom: 12rpx;

					&:last-child {
						margin-bottom: 0;
					}

					.info-label {
						font-size: 26rpx;
						color: #8F97A2;
					}

					.info-value {
						font-size: 26rpx;
						color: #2C2622;
						font-weight: 500;
					}
				}
			}
		}
	}

	.post-footer {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 24rpx;
		border-top: 1rpx solid #f0f0f0;

		.post-tags {
			.type-tag {
				display: inline-flex;
				align-items: center;
				padding: 8rpx 16rpx;
				border-radius: 16rpx;
				font-size: 22rpx;
				font-weight: 500;

				&.type-daily {
					background: #e6f7ff;
					color: #1890ff;
				}

				&.type-lost {
					background: #fff7e6;
					color: #fa8c16;
				}

				&.type-idle {
					background: #f6ffed;
					color: #52c41a;
				}

				&.type-default {
					background: #f0f0f0;
					color: #666;
				}

				.tag-icon {
					margin-right: 6rpx;
					font-size: 18rpx;
				}

				.tag-text {
					font-size: 22rpx;
				}
			}
		}

		.post-stats {
			display: flex;
			align-items: center;
			gap: 24rpx;

			.stat-item {
				display: flex;
				align-items: center;
				gap: 6rpx;

				.stat-icon {
					font-size: 24rpx;
					transition: all 0.3s ease;

					&.liked {
						transform: scale(1.2);
					}
				}

				.stat-count {
					font-size: 24rpx;
					color: #8F97A2;
				}
			}
		}
	}

	.load-more {
		text-align: center;
		padding: 24rpx;

		.loading-content {
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 12rpx;

			.loading-spinner {
				width: 28rpx;
				height: 28rpx;
				border: 2rpx solid #f3f3f3;
				border-top: 2rpx solid #FE6100;
				border-radius: 50%;
				animation: spin 1s linear infinite;
			}

			.loading-text {
				font-size: 24rpx;
				color: #8F97A2;
			}
		}
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.menu-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: transparent;
		z-index: 50;
	}
</style>